package org.itboys.mobile.service.mongo.web.dynamic;

import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.entity.lasted.SundayUpload;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.dynamic.SundayDynamic;
import org.itboys.mobile.entity.mongo.dynamic.SundayDynamicProduct;
import org.itboys.mobile.entity.mysql.order.SundayOrderProduct;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年4月26日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_移动端（通用）_动态_=_sevice。如果属性不够，请自行填充
 */
@Service
public class SundayDynamicService extends BaseMongoService<SundayDynamic>{
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayProductMapper productMapper;
    @Autowired
    private SundayDynamicProductService dynamicProductService;
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayDynamic> getEntityClass() {
        return SundayDynamic.class;
    }


    /**
     * 分页查询动态
     * @param request
     * @param type
     * @return
     */
    public PageResult<SundayDynamic> selectDynamic(HttpServletRequest request, Integer type) {
        Map<String, Object> param =new HashMap<String,Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        if(type!=null){
            param.put("type",type);
        }
        Map<String, String> containsparam =ParamUtil.packageMongoVagueParam(request,"memberName","content");
        return super.containpageQuery(request,containsparam,param);
    }

    /**
     *  查询动态详情。后台
     * @param dynamicId
     * @param type
     * @return
     */
    public SundayDynamic findOne(Long dynamicId,Integer type){
        SundayDynamic dynamic=null;
        if(LongUtil.isNotZreo(dynamicId)){
            dynamic = super.getById(dynamicId);
            //TianJieProduct
            //关联图片
            List<SundayUploadDto> images = uploadService.selectNoPage(dynamic.getId(),SundayDynamic.class.getSimpleName());
            dynamic.setImages(images);
            //关联商品
            dynamic.setProducts(dynamicProductService.selectProduct(dynamicId));
        }else{
            dynamic=new SundayDynamic();
            dynamic.setId(dynamicId);
            dynamic.setType(type);



        }

        return dynamic;
    }
    /**
     * 生成动态（达人试用/本地爱购）
     * @param dynamic
     * @param productIds
     * @param imageFiles
     * @throws Exception
     */
    public void saveDynamic(SundayDynamic dynamic,List<Long> productIds,MultipartFile[] imageFiles)throws  Exception{
      //  SundayDynamic dynamic = new SundayDynamic();
      //  dynamic.setType(type);

        //编辑
        if(LongUtil.isNotZreo(dynamic.getId())){

            super.updateExceptEmpty(dynamic.getId(),dynamic);
        }else{

            dynamic.setDzNumber(0);
            dynamic.setPlNumber(0);
            super.save(dynamic);

        }
        logger.info("productIds="+productIds);
        //保存商品
        if(ListUtil.isNotNull(productIds)){
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("ids",productIds);
            List<SundayProduct> products = productMapper.select(param);
            List<SundayDynamicProduct> dynamicProducts = new ArrayList<>();
            for(SundayProduct product:products){
                dynamicProducts.add(new SundayDynamicProduct(dynamic.getId(), product.getId(), product.getName(),resourceHolder.getStringValue("imgRoot")+product.getImage(), product.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
            }
            if(ListUtil.isNotNull(dynamicProducts)){
                dynamicProductService.batchSaveWithoutLogin(dynamicProducts);
            }
        }

        //保持动态的图片
        uploadService.uploadMultiWithRecord(imageFiles,dynamic.getId(),SundayDynamic.class.getSimpleName(),"动态"+dynamic.getId()+",的轮播图");
    }


}
